package br.zeus.lemenu

class ItemController {

	def list = {
		if(Item.count() == 0) {
			flash.message = "${message(code: 'item.listar.inexistente')}"
			redirect(action: "create")
		}
		
		[itemInstanceList: Item.list(params), itemInstanceTotal: Item.count()]
	}

	def create = {
		def itemInstance = new Item()
		itemInstance.properties = params
		return [itemInstance: itemInstance]
	}

	def save = {
		def itemInstance = new Item(params)
		def okcontents = [
			'image/png',
			'image/jpeg',
			'image/jpg',
			'image/gif'
		]
		def arquivo = request.getFile('arquivo')

		if(!arquivo.isEmpty()){
			if (!okcontents.contains(arquivo.getContentType())) {
				flash.message = "${message(code: 'item.novo.mime.invalido')}"
				render(view:'create')
			}
			
			String arquivoNome = arquivo.getOriginalFilename()
			String path = "web-app/img/"
			File file = new File(path)
			itemInstance.foto = "img/"+arquivoNome
			path = path+"/"+arquivoNome
			arquivo.transferTo(new File(path))
		} else {
			itemInstance.foto = "img/nophoto.jpg"
		}

		if (itemInstance.save(flush: true)) {
			flash.message = "${message(code: 'item.criado', args: [itemInstance.nome])}"
			redirect(action: "show", id: itemInstance.id)
		} else {
			render(view: "create", model: [itemInstance: itemInstance])
		}
	}

	def show = {
		def itemInstance = Item.get(params.id)
		if (!itemInstance) {
			flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'item.label', default: 'Item'), params.id])}"
			redirect(action: "list")
		} else {
			[itemInstance: itemInstance]
		}
	}
	
	def delete = {
		def selecteds = params.cbItem
		for(Integer selected : selecteds) {
			def item = Item.get(selected)
			if(item) {
				item.delete(flush:true)
			}
		}

		redirect(action: "list")
	}
}